<template>
  <div>
    <el-page-header @back="goBack" content="发表知识点">
    </el-page-header>

    <el-divider></el-divider>

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="知识点名称" prop="knowledge">
        <el-input v-model="ruleForm.knowledge"></el-input>
      </el-form-item>
      <el-form-item label="项目名称" prop="projectId">
        <el-select v-model="ruleForm.projectId" placeholder="请选择">
          <el-option
              v-for="item in projectListOptions"
              :key="item.id"
              :label="item.proName"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="知识点类别" prop="knowType">
        <el-input v-model="ruleForm.knowType"></el-input>
      </el-form-item>
      <el-form-item label="知识点简介" prop="knowDes">
        <el-input v-model="ruleForm.knowDes"></el-input>
      </el-form-item>
      <el-form-item label="上传图片" prop="knowUrl">
        <el-upload
            action="http://localhost:8989/upload"
            name="pic"
            :limit="1"
            list-type="picture-card"
            :on-success="handleSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">发表</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      projectListOptions: [],
      ruleForm: {
        knowledge: '',
        projectId: '',
        knowType: '',
        knowDes: '',
        knowUrl: '',
        state: ''
      },
      rules: {
        knowledge: [
          {required: true, message: '请输入知识点名称,方便查找', trigger: 'blur'},
          {min: 4, max: 50, message: '长度在 4 到 50 个字符', trigger: 'blur'}
        ],
        projectId: [
          {required: true, message: '请选择对应的项目,方便同学们学习', trigger: 'blur'}
        ],
        knowType: [
          {required: true, message: '请输入知识点对应的类型,例如:Java、HTML、Vue、报错等', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        knowDes: [
          {required: true, message: '请对知识点进行描述', trigger: 'blur'},
          {max: 500, message: '长度在500个字符以内', trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    goBack() {
      this.$router.push({path: '/knows'})
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get('http://localhost:8989/remove?url='+file.response).then(function () {
        console.log("删除服务器图片完成!")
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(response){
      this.ruleForm.knowUrl = response;
    },
    loadProjectList() {
      console.log('loadProjectList');
      let url = 'http://localhost:8989/projects/list';
      console.log('url = ' + url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        this.projectListOptions = responseBody.data;
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:8989/knows/add-new';
          console.log('url = ' + url);
          let formData = this.qs.stringify(this.ruleForm, {arrayFormat: 'repeat'});
          console.log('formData = ' + formData);
          this.axios
              .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
              .post(url, formData).then((response) => {
            let responseBody = response.data;
            console.log('responseBody = ');
            console.log(responseBody);
            if (responseBody.state == 20000) {
              this.$message({
                message: '发表知识点成功！',
                type: 'success'
              });
              this.resetForm(formName);
            } else {
              this.$message.error(responseBody.message);
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.loadProjectList();
  }
}
</script>